<?php
require __DIR__ . '/../bootstrap.php';

/* @var $em \Doctrine\ORM\EntityManager */
$em = require __DIR__ . '/../example/em.php';

$q = $em->createQuery("delete from Entity\SimOwner s");
$numDelete = $q->execute();

$q = $em->createQuery("select u from Entity\User u");
$res = $q->execute();

if (count($res)) {
    echo "Необходимо удалить всех пользователей!";
    exit();
}

$counter = 0;
$admin = new \Entity\User(array(
    'name' => 'admin',
    'group' => $em->find("Entity\Group", 1),
    'password' => md5('root'),
    'fullName' => 'ADMIN'
));

$em->persist($admin);

$agent1 = getAgent($admin, $em);
$agent2 = getAgent($admin, $em);
$agent3 = getAgent($admin, $em);

$em->persist($agent1);
$em->persist($agent2);
$em->persist($agent3);

$em->persist(getSubAgent($agent1, $em));
$em->persist(getSubAgent($agent1, $em));
$em->persist(getSubAgent($agent1, $em));

$em->persist(getSubAgent($agent2, $em));
$em->persist(getSubAgent($agent2, $em));
$em->persist(getSubAgent($agent2, $em));

$em->persist(getSubAgent($agent3, $em));
$em->persist(getSubAgent($agent3, $em));
$em->persist(getSubAgent($agent3, $em));

$em->flush();

addSims($em);

echo "Данные загружены!";

function getAgent(\Entity\User $parent, \Doctrine\ORM\EntityManager $em)
{
    global $counter;
    $counter++;
    $data = array(
        'name' => 'Agent ' . $counter,
        'password' => md5('root'),
        'parent' => $parent,
        'group' => $em->find("Entity\Group", 2),
        'fullName' => 'AGENT',
        'balance' => '0'
    );
    return new \Entity\User($data);
}

function getSubAgent(\Entity\User $parent, \Doctrine\ORM\EntityManager $em)
{
    global $counter;
    $counter++;
    $data = array(
        'name' => 'Subagent ' . $counter,
        'password' => md5('root'),
        'parent' => $parent,
        'group' => $em->find("Entity\Group", 3),
        'fullName' => 'SUBAGENT',
        'balance' => '0'
    );
    return new \Entity\User($data);
}

function addSims(\Doctrine\ORM\EntityManager $em)
{
    $users = $em->getRepository("Entity\User")->findAll();
    $sims = $em->getRepository("Entity\Sim")->findAll();
    foreach ($sims as $sim) {
        shuffle($users);
        $user = $users[0];
        $simOwner = new \Entity\SimOwner();
        $simOwner->setUser($user);
        $simOwner->setSim($sim);
        $em->persist($simOwner);
    }
    $em->flush();

}


